# -*- coding: utf-8 -*-
from typing import Annotated

from fastapi import APIRouter, Path, Query, Depends, Request
from fastapi_limiter.depends import RateLimiter

from App.common.pagination import paging_data, DependsPagination
from App.common.respones.response_schema import ResponseModel, response_base
from App.common.security.jwt import DependsJwtAuth
from App.database.mysql import CurrentSession

# 动态导入模型和Schema
from App.app.admin.services.sys_user_service import SysUserService
from App.app.admin.schemas.sys_user_schema import (
    CreateSysUserParam,
    UpdateSysUserParam, SysUserSchema, RegisterUserParam, ResetPasswordParam, GetUserInfoDetails,
    GetCurrentUserInfoDetail, UpdateMeParam
)
from App.utils.serializers import select_as_dict

router = APIRouter(prefix="/user")


@router.post("/register", summary="注册用户", description="用户自主注册时使用该接口",
             dependencies=[Depends(RateLimiter(times=20, minutes=1))])
async def register_user(obj_in: RegisterUserParam) -> ResponseModel:
    sys_user = await SysUserService.register_user(obj_in=obj_in)
    return response_base.success(data=SysUserSchema.model_validate(sys_user))


@router.get('/{pk}', summary='获取用户详情', description="根据ID获取用户详情",
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def get_sys_user(pk: Annotated[int, Path(...)]) -> ResponseModel:
    sys_user = await SysUserService.get(pk=pk)
    data = GetUserInfoDetails(**select_as_dict(sys_user))
    return response_base.success(data=data)


@router.post(
    '',
    summary='新增用户(用于后台管理员新增用户操作)', description="新增用户(用于后台管理员新增用户操作)",
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth]
)
async def create_sys_user(request: Request, obj_in: CreateSysUserParam) -> ResponseModel:
    data = await SysUserService.create(request=request, obj_in=obj_in)
    return response_base.success(data=data)


@router.get(
    '',
    summary='（模糊条件）分页获取所有用户',
    description='（模糊条件）分页获取所有用户',
    dependencies=[
        Depends(RateLimiter(times=20, minutes=1)),
        DependsJwtAuth,
        DependsPagination
    ],
)
async def get_pagination_users(
        db: CurrentSession,
        nickname: Annotated[str | None, Query()] = None,
        username: Annotated[str | None, Query()] = None,
        phone: Annotated[str | None, Query()] = None,
        status: Annotated[str | None, Query()] = None,
        role_id: Annotated[str | None, Query()] = None,
        sort_field: Annotated[str | None, Query()] = None,
        sort_order: Annotated[str | None, Query()] = None
) -> ResponseModel:
    user_select = await SysUserService.get_select(nickname=nickname, username=username, phone=phone, status=status,
                                                  role_id=role_id, sort_field=sort_field, sort_order=sort_order)
    page_data = await paging_data(db, user_select, GetCurrentUserInfoDetail)
    return response_base.success(data=page_data)


@router.put('', summary='更新用户信息', description="更新用户信息（非管理员账户只能更新自己的信息）",
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def update_sys_user(request: Request, obj_in: UpdateSysUserParam) -> ResponseModel:
    count = await SysUserService.update(request=request, obj_in=obj_in)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.delete(
    '/{pk}',
    summary='删除用户（物理删除）',
    description='删除用户（物理删除）',
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def delete_sys_user(pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.delete(pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.delete(
    '/logoff/{pk}',
    summary='注销用户（逻辑删除）',
    description='注销用户（逻辑删除）',
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def logoff_sys_user(pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.logoff(pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.get('/query/me', summary='获取当前用户信息', description="一般在更新用户信息后调用，来获取最近的用户信息",
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def get_current_user(request: Request) -> ResponseModel:
    cache_user = request.user
    sys_user = await SysUserService.get(pk=cache_user.id)
    data = GetCurrentUserInfoDetail.model_validate(sys_user)
    return response_base.success(data=data)


@router.put('/super/{pk}', summary='修改用户超级权限', description='修改用户超级权限',
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def super_set(request: Request, pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.update_super(request=request, pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.put('/staff/{pk}', summary='修改用户后台登录权限', description='修改用户后台登录权限',
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def staff_set(request: Request, pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.update_staff(request=request, pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.put('/status/{pk}', summary='修改用户状态', description='修改用户状态',
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def status_set(request: Request, pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.update_status(request=request, pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.put('/multi/{pk}', summary='修改用户多点登录状态', description='修改用户多点登录状态',
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def multi_set(request: Request, pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.update_multi_login(request=request, pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.post('/password/reset/{pk}', summary='重置其他用户的密码', description='重置其他用户的密码',
             dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def password_reset(request: Request, pk: Annotated[int, Path(...)]) -> ResponseModel:
    count = await SysUserService.pwd_reset(request=request, pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.put('/password/me', summary='修改当前登录用户的密码', description='修改当前登录用户的密码',
             dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def password_reset(request: Request, obj_in: ResetPasswordParam) -> ResponseModel:
    count = await SysUserService.pwd_change(request=request, obj_in=obj_in)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.put('/info/me', summary='修改当前登录用户信息', description="修改当前登录用户信息",
            dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def get_current_user(request: Request, obj_in: UpdateMeParam) -> ResponseModel:
    count = await SysUserService.update_me(obj_in=obj_in)
    if count > 0:
        return response_base.success()
    return response_base.fail()
